<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    v-loading="formLoading"
    label-width="0px"
    :inline-message="true"
  >
    <el-table :data="formData" class="-mt-10px">
      <el-table-column label="序号" type="index" width="100" />
      <el-table-column label="县乡村编号" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.areaId`" :rules="formRules.areaId" class="mb-0px!">
            <!--            <el-select v-model="row.areaId" placeholder="请选择县乡村编号">
                            <el-option label="请选择字典生成" value="" />
                        </el-select>-->
            <el-tree-select
              v-model="row.areaId"
              :data="areaTree"
              :props="defaultProps"
              check-strictly
              default-expand-all
              placeholder="请选择县乡村编号"
            />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="户数" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.familyNum`" :rules="formRules.familyNum" class="mb-0px!">
            <el-input v-model="row.familyNum" placeholder="请输入户数" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="金额" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.amount`" :rules="formRules.amount" class="mb-0px!">
            <el-input v-model="row.amount" placeholder="请输入金额" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="余额" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.balance`" :rules="formRules.balance" class="mb-0px!">
            <el-input v-model="row.balance" placeholder="请输入余额" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="60">
        <template #default="{ $index }">
          <el-button @click="handleDelete($index)" link>—</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-form>
  <el-row justify="center" class="mt-3">
    <el-button @click="handleAdd" round>+ 添加数据统计子</el-button>
  </el-row>
</template>
<script setup lang="ts">
import { DataStatsApi } from '@/api/circ/datastats'
import { AreaApi, AreaVO } from '@/api/circ/area'
import { defaultProps, handleTree } from '@/utils/tree'

const props = defineProps<{
  pid: undefined // 数据统计主表id（主表的关联字段）
}>()
const formLoading = ref(false) // 表单的加载中
const formData = ref([])
const formRules = reactive({
  pid: [{ required: true, message: '数据统计主表id不能为空', trigger: 'blur' }],
  areaId: [{ required: true, message: '县乡村编号不能为空', trigger: 'change' }],
  familyNum: [{ required: true, message: '户数不能为空', trigger: 'blur' }],
  amount: [{ required: true, message: '金额不能为空', trigger: 'blur' }],
  balance: [{ required: true, message: '余额不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const areaTree = ref() // 树形结构

/** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(
  () => props.pid,
  async (val) => {
    // 1. 重置表单
    formData.value = []
    // 2. val 非空，则加载数据
    if (!val) {
      return
    }
    try {
      formLoading.value = true
      formData.value = await DataStatsApi.getDataStatsChildListByPid(val)
    } finally {
      formLoading.value = false
    }
    await getAreaTree()
  },
  { immediate: true }

)

/** 新增按钮操作 */
const handleAdd = async () => {
  const row = {
    id: undefined,
    pid: undefined,
    areaId: undefined,
    familyNum: undefined,
    amount: undefined,
    balance: undefined
  }
  row.pid = props.pid
  await getAreaTree()
  formData.value.push(row)
}

/** 删除按钮操作 */
const handleDelete = (index) => {
  formData.value.splice(index, 1)
}

/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}

/** 表单值 */
const getData = () => {
  return formData.value
}

/** 获得县乡村树 */
const getAreaTree = async () => {
  areaTree.value = []
  const data = await AreaApi.getAreaList('')
  const root: Tree = { id: 0, name: '顶级县乡村', children: [] }
  root.children = handleTree(data, 'id', 'parentId')
  areaTree.value.push(root)
}

defineExpose({ validate, getData })
</script>
